﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.ReadApi.Command;
using U.B.ReadApi.Dto;
using U.B.Repistory;

namespace U.B.ReadApi.CommandHander
{
    public class LoginCommandHander : IRequestHandler<LoginCommand, ApiResult<UserDto>>
    {
        private readonly IRepistory<User> Userrepistory;
        private readonly IRepistory<UserRole> _urRep;
        private readonly IRepistory<Role> _roleRep;

        public LoginCommandHander(IRepistory<User> userRep, IRepistory<UserRole> urRep, IRepistory<Role> roleRep)
        {
            Userrepistory = userRep;
            _urRep = urRep;
            _roleRep = roleRep;
        }
        /// <summary>
        /// 处理登录命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public  async Task<ApiResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDto> apiResult = new ApiResult<UserDto>();
            string strToken = this.CreateTokenString();
            var u = Userrepistory.GetAll().FirstOrDefault(x => x.UserName == request.UserName);

            var list = from a in Userrepistory.GetAll()
                       join b in _urRep.GetAll() on a.UserId equals b.UserId
                       join c in _roleRep.GetAll() on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName
                       select new UserDto
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserSex = a.UserSex,
                           Province = a.Province,
                           UserPwd = a.UserPwd,
                           City = a.City,
                           County = a.County,
                           UserAddress = a.UserAddress,
                           Updatedate = a.Updatedate,
                           Updateor = a.Updateor,
                           CreationDate = a.CreationDate,
                           Creator = a.Creator,
                           RoleName = c.RoleName,
                           RoleId = c.RoleId,
                           DepartmentId = a.DepartmentId,
                           PowerId = a.PowerId,
                       };
            if (u != null)
            {
                if (u.UserPwd == request.UserPwd)
                {
                    apiResult.code = Renum.登录成功;
                    apiResult.Message = "登录成功";
                    apiResult.Data = list.ToList()[0];

                }
                else
                {
                    apiResult.code = Renum.登录失败;
                    apiResult.Message = "密码错误";

                }

            }
            else
            {
                apiResult.code = Renum.名字不得重复;
                apiResult.Message = "用户不存在";

            }
            apiResult.token = strToken;
            return await Task.FromResult(apiResult);//行了返回了我测试一下
        }
        /// <summary>
        /// 生成 JWT Token（令牌）然后该怎么做《》
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
